package com.learn.eduuserboot.until;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.Date;

@ConfigurationProperties("jwt.config")
@EnableConfigurationProperties(JwtUtil.class)
@Service
public class JwtUtil {
    //盐
    private String key ;
    //过期时间
    private long ttl ;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }


    /**
     * 生成JWT
     * @param id 用户id
     * @param portrait 用户信息
     * @param name 自定义key-value 角色
     * @return
     */
    public String createJWT(String id, String portrait, String name) {
        //signWith(SignatureAlgorithm.HS256, key) 设置加密方式，和盐 。盐自己规定
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(portrait)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("roles", name);
        if (ttl > 0) {
            //设置过期时间
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

}
